<template>
    <div class="container">
        <div style="display: flex">
            <h2 style="">公共聊天室</h2>
        </div>
        <div class="marquee-container">
            <el-carousel :interval="3000" arrow="never" indicator-position="none" type="outside"
                         effect="scrollx">
                <el-carousel-item v-for="(text, index) in texts" :key="index">
                    <div class="marquee-item">
                        <h2 style="color: rgba(227,7,106,0.96);"> {{ text }}</h2>
                    </div>
                </el-carousel-item>
            </el-carousel>
        </div>
        <div class="chat-wrapper">
            <div class="message-list">
                <ul>
                        <li v-for="item in messagess">
                            <div style="max-width: 100%">
                                <p style=" text-align: center;">{{ item.date }}</p>
                                <div style="display: flex">
                                    <strong style="white-space: nowrap">{{ item.content + "  " }}:</strong>
                                    <strong style="word-break: break-all;">{{ item.sender }}</strong></div>
                            </div>
                        </li>
                    <li v-for="item in messages">
                        <div style="max-width: 100%">
                            <p style="text-align: center;">{{ item.date }}</p>
                            <div style="display: flex">
                                <strong style="white-space: nowrap">{{ item.sender + "  " }}:</strong>
                                <strong style="word-break: break-all;">{{ item.content }}</strong></div>
                        </div>
                    </li>
                </ul>
            </div>
        </div>
        <div class="input-wrapper" style="">
            <el-input v-model="message.sender" placeholder="请输入聊天信息"></el-input>
            <el-button @click="sendMessage(),addmessage()">发送</el-button>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
import {getAvatar} from "@/views/header/Headeruser";
import {addmassage, getmassage, getOnlineCount} from "@/views/chatroom/chatroom";

export default {
    data() {
        return {
            texts: [
                '文明交流',
                '禁止发布其他广告',
            ],
            messages: [],
            messagess:{},
            pepo:'',
            message: {
                userid: '',
                content: '',
                sender: '',
            },
            websocket: null,
        };
    },
    mounted() {
        this.getData();//初次加载
        // // 创建WebSocket连接
        // const socket = new WebSocket("ws://localhost:9999/chat");
        // // 监听WebSocket消息
        // socket.onmessage = (event) => {
        //     const message = JSON.parse(event.data);
        //     this.messages.push(message);
        // };

        //判断浏览器是否支持websocket
        if ('WebSocket' in window) {
          // this.websocket = new WebSocket('ws://localhost:9999/chat/' + this.$store.state.user.usernickname);
          this.websocket = new WebSocket('ws://111.229.186.198:8081/chat/' + this.$store.state.user.usernickname);
        } else {
            this.$message.error('当前浏览器不支持websocket消息通知');
        }

        //连接成功建立的回调方法
        this.websocket.onopen = event => {
            console.log("ws建立连接成功");
        }

        //连接关闭的回调方法
        this.websocket.onclose = event => {
            console.log("ws连接关闭");
        }

        //接收到消息的回调方法
        this.websocket.onmessage = event => {
            // console.log("服务器返回消息： " + event.data);
            //json字符串转json对象
            var jsonObj = JSON.parse(event.data);
            this.messages.push(jsonObj)
            console.log(this.messages)
        }

        //连接发生错误的回调方法
        this.websocket.onerror = event => {
            this.$message.error('websocket通信发生错误,请先进行登录！')
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = () => {
            this.websocket.close();
        }
    },
    methods: {
        //获取后台接口数据
        getData() {
            getmassage().then(res => {
                this.messagess = res.data;
            })
        },
        //聊天记录存到数据库
        addmessage() {
            if (this.message.sender!==''){
                this.message.userid = this.$store.state.user.userid
                this.message.content = this.$store.state.user.usernickname
                addmassage(this.message).then(res => {
                    if (res === 200) {
                        this.$message.success("发送成功")
                        this.message.sender = " "
                    }else {
                        this.$message.error("请先输入内容")
                    }
                })
            }
        },
        // sendMessage() {
        //     // 发送HTTP请求到后端API
        //     axios.post('http://localhost:9999/chat', {
        //         username: 'Guest',
        //         content: this.inputMessage,
        //     }).then(() => {
        //         this.inputMessage = '';
        //     });
        // },

        sendMessage() {
            if (this.message.sender!==''){
                this.websocket.send(this.message.sender);
                this.message.sender = " "
            }else{
                this.$message.error("请先输入内容")
            }
        }
    },
};
</script>

<style>
/*个人中心图标大小*/
.userMessage {
    width: 35px;
    border-radius: 50%;
}

/*文字跑马灯*/
.marquee-container {
    width: 330px;
    height: 30px;
    overflow: hidden;
}

.marquee-item {
    right: 45%;
    top: 50%;
    height: 20px;
    line-height: 25px;
    text-align: center;
}


.container {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
}

.chat-wrapper {
    width: 320px;
    display: flex;
    flex-direction: column;
    height: 600px;
    border: 1px solid #ccc;
    padding: 10px;
    overflow-y: scroll;
}

.message-list {
    flex: 1;
}

.input-wrapper {
    display: flex;
    margin-top: 10px;
}

.el-input,
.el-button {
    margin-right: 10px;
}
</style>
